<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const scheduleList = ref<any[]>([]);
const formVisible = ref(false);
const formRef = ref();
const selectedRowKeys = ref<string[]>([]);

const searchForm = reactive({
  keyword: '',
  maintenanceType: '',
  status: '',
  resourceType: '',
});

const formData = reactive({
  id: '',
  name: '',
  resourceId: '',
  resourceName: '',
  maintenanceType: '',
  description: '',
  plannedDate: '',
  estimatedDuration: 1,
  estimatedCost: 0,
  priority: 'MEDIUM',
  assignee: '',
  notes: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 维护类型选项
const maintenanceTypeOptions = [
  { label: '预防性维护', value: 'PREVENTIVE' },
  { label: '定期维护', value: 'PERIODIC' },
  { label: '紧急维修', value: 'EMERGENCY' },
  { label: '设备升级', value: 'UPGRADE' },
];

// 状态选项
const statusOptions = [
  { label: '待执行', value: 'PENDING' },
  { label: '执行中', value: 'IN_PROGRESS' },
  { label: '已完成', value: 'COMPLETED' },
  { label: '已取消', value: 'CANCELLED' },
];

// 优先级选项
const priorityOptions = [
  { label: '低', value: 'LOW' },
  { label: '中', value: 'MEDIUM' },
  { label: '高', value: 'HIGH' },
  { label: '紧急', value: 'URGENT' },
];

// 资源类型选项
const resourceTypeOptions = [
  { label: '设备', value: 'EQUIPMENT' },
  { label: '设施', value: 'FACILITY' },
  { label: '车辆', value: 'VEHICLE' },
  { label: '系统', value: 'SYSTEM' },
];

// 表格列定义
const columns = [
  {
    title: '计划名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 150,
  },
  {
    title: '维护类型',
    dataIndex: 'maintenanceType',
    key: 'maintenanceType',
    width: 120,
  },
  {
    title: '计划日期',
    dataIndex: 'plannedDate',
    key: 'plannedDate',
    width: 120,
  },
  {
    title: '预计时长',
    dataIndex: 'estimatedDuration',
    key: 'estimatedDuration',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: '1',
        name: '空调系统年度维护',
        resourceId: 'AC001',
        resourceName: '中央空调系统',
        maintenanceType: 'PREVENTIVE',
        description: '年度预防性维护，包括清洁、检查、更换滤网等',
        plannedDate: '2024-03-15',
        estimatedDuration: 4,
        estimatedCost: 2000,
        priority: 'MEDIUM',
        status: 'PENDING',
        assignee: '张师傅',
        notes: '需要提前准备滤网和清洁剂',
      },
      {
        id: '2',
        name: '电梯紧急维修',
        resourceId: 'EL001',
        resourceName: '客梯1号',
        maintenanceType: 'EMERGENCY',
        description: '电梯运行异常，需要紧急检查和维修',
        plannedDate: '2024-03-10',
        estimatedDuration: 2,
        estimatedCost: 1500,
        priority: 'URGENT',
        status: 'IN_PROGRESS',
        assignee: '李师傅',
        notes: '已联系电梯公司技术人员',
      },
      {
        id: '3',
        name: '锅炉设备升级',
        resourceId: 'BL001',
        resourceName: '锅炉系统',
        maintenanceType: 'UPGRADE',
        description: '升级锅炉控制系统，提高能效',
        plannedDate: '2024-03-20',
        estimatedDuration: 8,
        estimatedCost: 15_000,
        priority: 'HIGH',
        status: 'PENDING',
        assignee: '王师傅',
        notes: '需要停用锅炉24小时',
      },
    ];

    scheduleList.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error('加载维护计划失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    maintenanceType: '',
    status: '',
    resourceType: '',
  });
  handleSearch();
};

// 打开表单
const openScheduleForm = (type: 'create' | 'edit', record?: any) => {
  formVisible.value = true;
  if (type === 'edit' && record) {
    Object.assign(formData, record);
  } else {
    Object.assign(formData, {
      id: '',
      name: '',
      resourceId: '',
      resourceName: '',
      maintenanceType: '',
      description: '',
      plannedDate: '',
      estimatedDuration: 1,
      estimatedCost: 0,
      priority: 'MEDIUM',
      assignee: '',
      notes: '',
    });
  }
};

// 保存表单
const saveSchedule = async () => {
  try {
    await formRef.value.validate();

    // 模拟保存
    if (formData.id) {
      // 编辑
      const index = scheduleList.value.findIndex(
        (item) => item.id === formData.id,
      );
      if (index !== -1) {
        scheduleList.value[index] = { ...formData };
      }
      message.success('维护计划更新成功');
    } else {
      // 新增
      const newSchedule = {
        ...formData,
        id: Date.now().toString(),
        status: 'PENDING',
      };
      scheduleList.value.unshift(newSchedule);
      message.success('维护计划创建成功');
    }

    formVisible.value = false;
    loadData();
  } catch (error) {
    console.error('保存失败:', error);
  }
};

// 删除计划
const deleteSchedule = (id: string) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个维护计划吗？',
    onOk: () => {
      scheduleList.value = scheduleList.value.filter((item) => item.id !== id);
      message.success('删除成功');
      loadData();
    },
  });
};

// 更新状态
const updateStatus = (id: string, status: string) => {
  const schedule = scheduleList.value.find((item) => item.id === id);
  if (schedule) {
    schedule.status = status;
    message.success('状态更新成功');
  }
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="maintenance-schedule">
    <!-- 搜索区域 -->
    <Card title="搜索条件" :bordered="false" style="margin-bottom: 16px">
      <Row :gutter="16">
        <Col :span="6">
          <Form.Item label="关键词">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="请输入计划名称或资源名称"
              allow-clear
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="维护类型">
            <Select
              v-model:value="searchForm.maintenanceType"
              placeholder="请选择维护类型"
              allow-clear
              :options="maintenanceTypeOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              :options="statusOptions"
            />
          </Form.Item>
        </Col>
        <Col :span="6">
          <Form.Item label="资源类型">
            <Select
              v-model:value="searchForm.resourceType"
              placeholder="请选择资源类型"
              allow-clear
              :options="resourceTypeOptions"
            />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col :span="24" style="text-align: right">
          <Space>
            <Button @click="resetSearch">重置</Button>
            <Button type="primary" @click="handleSearch">搜索</Button>
          </Space>
        </Col>
      </Row>
    </Card>

    <!-- 数据表格 -->
    <Card :bordered="false">
      <div class="table-toolbar">
        <Space>
          <Button type="primary" @click="openScheduleForm('create')">
            <IconifyIcon icon="mdi:plus" />
            创建计划
          </Button>
          <Button
            :disabled="selectedRowKeys.length === 0"
            @click="() => console.log('批量操作')"
          >
            批量操作
          </Button>
        </Space>
      </div>

      <Table
        :columns="columns"
        :data-source="scheduleList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{
          selectedRowKeys,
          onChange: (keys: any[]) => (selectedRowKeys = keys as string[]),
        }"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'maintenanceType'">
            <Tag :color="getMaintenanceTypeColor(record.maintenanceType)">
              {{ getMaintenanceTypeLabel(record.maintenanceType) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityLabel(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button
                type="link"
                size="small"
                @click="openScheduleForm('edit', record)"
              >
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                @click="deleteSchedule(record.id)"
              >
                删除
              </Button>
              <Select
                v-if="record.status === 'PENDING'"
                size="small"
                style="width: 100px"
                placeholder="更新状态"
                @change="(value) => updateStatus(record.id, value)"
              >
                <SelectOption value="IN_PROGRESS">开始执行</SelectOption>
                <SelectOption value="CANCELLED">取消</SelectOption>
              </Select>
              <Select
                v-else-if="record.status === 'IN_PROGRESS'"
                size="small"
                style="width: 100px"
                placeholder="更新状态"
                @change="(value) => updateStatus(record.id, value)"
              >
                <SelectOption value="COMPLETED">完成</SelectOption>
                <SelectOption value="CANCELLED">取消</SelectOption>
              </Select>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 维护计划表单 -->
    <Modal
      v-model:open="formVisible"
      :title="formData.id ? '编辑维护计划' : '创建维护计划'"
      width="800px"
      @ok="saveSchedule"
    >
      <Form
        ref="formRef"
        :model="formData"
        :rules="{
          name: [{ required: true, message: '请输入计划名称' }],
          resourceName: [{ required: true, message: '请输入资源名称' }],
          maintenanceType: [{ required: true, message: '请选择维护类型' }],
          plannedDate: [{ required: true, message: '请选择计划日期' }],
        }"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="计划名称" name="name">
              <Input
                v-model:value="formData.name"
                placeholder="请输入计划名称"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="资源名称" name="resourceName">
              <Input
                v-model:value="formData.resourceName"
                placeholder="请输入资源名称"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="维护类型" name="maintenanceType">
              <Select
                v-model:value="formData.maintenanceType"
                placeholder="请选择维护类型"
                :options="maintenanceTypeOptions"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="计划日期" name="plannedDate">
              <DatePicker
                v-model:value="formData.plannedDate"
                placeholder="请选择计划日期"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="预计时长(小时)" name="estimatedDuration">
              <InputNumber
                v-model:value="formData.estimatedDuration"
                :min="1"
                style="width: 100%"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="预计成本" name="estimatedCost">
              <InputNumber
                v-model:value="formData.estimatedCost"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="优先级" name="priority">
              <Select
                v-model:value="formData.priority"
                placeholder="请选择优先级"
                :options="priorityOptions"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="负责人" name="assignee">
              <Input
                v-model:value="formData.assignee"
                placeholder="请输入负责人"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="维护描述" name="description">
          <Input.TextArea
            v-model:value="formData.description"
            placeholder="请输入维护描述"
            :rows="3"
          />
        </FormItem>
        <FormItem label="备注" name="notes">
          <Input.TextArea
            v-model:value="formData.notes"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.maintenance-schedule {
  padding: 20px;
}

.table-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}
</style>
